<template>
  <div>
    <el-collapse-transition>
      <card-search v-if="searchCardShow">
        <el-form ref="form" :model="form" label-width="80px" :inline="true">
          <el-form-item label="设备类别">
            <el-select
              v-model="value"
              placeholder="请选择"
              style="width: 250px"
              clearable
            >
              <el-option
                v-for="item in options"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
                clearable
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button class="btn-search" round icon="el-icon-search" size="medium"
              >搜索</el-button
            >
            <el-button class="btn-search" round icon="el-icon-refresh" size="medium"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </card-search>
    </el-collapse-transition>

    <card-table style="height: calc(100vh - 100px)">
      <div class="card-table-header">
        <div class="card-table-header-btns">
          <el-button
            v-if="isSuperAdmin || hasPermission('system:versionManage:add')"
            class="btn-search"
            size="small"
            icon="el-icon-plus"
            @click="handleClick(null, 'add')"
            >新增</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('system:versionManage:edit')"
            class="btn-search"
            size="small"
            icon="el-icon-edit"
            :disabled="btnDisabled"
            @click="handleClick(null, 'edit')"
            >编辑</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('system:versionManage:remove')"
            class="btn-search"
            size="small"
            icon="el-icon-delete"
            :disabled="btnDisabled"
            @click="handleClick(null, 'delete')"
            >删除</el-button
          >
          <el-button
            class="btn-search"
            size="small"
            icon="el-icon-upload2"
            v-if="isSuperAdmin || hasPermission('system:versionManage:export')"
            >导出</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('monitor:job:changeStatus')"
            class="btn-search"
            size="small"
            icon="el-icon-upload"
            @click="handleClick(null, 'run')"
          >
            执行升级任务</el-button
          >
          <el-input
            v-if="isSuperAdmin || hasPermission('system:versionManage:list')"
            style="width: 250px; margin-left: 10px"
            clearable
            placeholder="请输入版本号"
            size="small"
            ><el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
        <div class="card-table-header-actions">
          <table-action
            :table-header="tableHeader"
            :search-show="isSuperAdmin || hasPermission('system:versionManage:list')"
            @check-change="handleCheckChange"
            @search-click="handleSearchClick"
            @init-click="handleInitClick"
          />
        </div>
      </div>
      <el-table
        :key="tableKey"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :header-cell-style="{ background: '#eff3f8', color: '#333' }"
        border
        stripe
        :default-sort="{ prop: 'date', order: 'descending' }"
        :max-height="tableHeight"
        @selection-change="handleSelectionChange"
        size="small"
        highlight-selection-row
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="item in tableHeader"
          v-if="item.visible"
          :key="item.prop"
          :label="item.title"
          :min-width="item.width"
          :prop="item.prop"
          sortable
          :align="item.align"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <div v-if="item.prop === 'updateSet'">
              <div class="link-type" @click="handleClick(scope.row, 'updateSet')">
                <el-tooltip content="设置固件更新的SN范围" placement="right">
                  <i class="el-icon-setting" style="color: #165eff"></i
                ></el-tooltip>
              </div>
            </div>
            <div v-else-if="item.prop === 'link'" class="link-type">
              <i class="el-icon-link" style="color: #165eff"></i>
            </div>
            <div v-else-if="item.prop === 'orderUpdate'">
              <el-switch class="link-type" v-model="scope.row.orderUpdate"></el-switch>
            </div>
            <div v-else-if="item.prop === 'allUpdate'">
              <el-switch class="link-type" v-model="scope.row.allUpdate"></el-switch>
            </div>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <XyPagination
        :total="total"
        :pageSizeNum="pageSize"
        :pageNum="currentPage"
        @pagination="handlerPagination"
      ></XyPagination>
    </card-table>
    <DialogAddversion
      v-model="dialogVisible"
      :field="field"
      status="type"
      @close="
        () => {
          dialogVisible = false;
        }
      "
    ></DialogAddversion>
    <UpdateRange
      v-model="updateRangeVisible"
      :field="field"
      status="type"
      @close="
        () => {
          updateRangeVisible = false;
        }
      "
    ></UpdateRange>
  </div>
</template>
<script>
import CardSearch from "@/components/CardSearch";
import CardTable from "@/components/CardTable";
import TableAction from "@/components/TableAction";
import DialogAddversion from "./component/DialogAddversion.vue";
import UpdateRange from "./component/DialogUpdateRange.vue";
import XyPagination from "@/components/XyPagination";
import { hasPermission, isSuperAdmin } from "@/utils/hasBtnPermission";

export default {
  components: {
    CardSearch,
    CardTable,
    TableAction,
    DialogAddversion,
    UpdateRange,
    XyPagination,
  },
  data() {
    return {
      tableKey: 0, // 用于强制刷新表格
      searchCardShow: false,
      dialogVisible: false,
      updateRangeVisible: false,
      field: "",
      form: {},
      input: "",

      tableHeader: [
        {
          title: "设备类别",
          prop: "date",
          width: "100",
          align: "center",
          visible: true,
        },
        {
          title: "版本号",
          prop: "name",
          width: "100",
          align: "center",
          visible: true,
        },
        {
          title: "更新说明",
          prop: "address",
          width: "200",
          align: "left",
          visible: true,
        },
        {
          title: "文件大小",
          prop: "status",
          width: "100",
          align: "center",
          visible: true,
        },
        {
          title: "下载链接",
          prop: "link",
          width: "120",
          align: "center",
          visible: true,
        },
        {
          title: "更新范围设置",
          prop: "updateSet",
          width: "120",
          align: "center",
          visible: true,
        },
        {
          title: "指定范围更新",
          prop: "orderUpdate",
          width: "120",
          align: "center",
          visible: true,
        },
        {
          title: "全部强制更新",
          prop: "allUpdate",
          width: "120",
          align: "center",
          visible: true,
        },
        {
          title: "下载次数",
          prop: "createTime",
          width: "120",
          align: "center",
          visible: true,
        },
        {
          title: "sha256码",
          prop: "sha",
          width: "150",
          align: "center",
          visible: true,
        },
        {
          title: "备注信息",
          prop: "mark",
          width: "150",
          align: "center",
          visible: true,
        },
      ],
      tableData: [
        {
          date: "1",
          name: "10.03.01",
          address: "sys_yser_sex",
          status: "15.6kb",
          createTime: "2021-01-01 10:10:10",
          allUpdate: true,
        },
        {
          date: "2",
          name: "18.03.01",
          address: "sys_show_hide",
          status: "正常",
          createTime: "2021-01-01 10:10:10",
        },
        {
          date: "3",
          name: "15.03.01",
          address: "sys_modal_disabled",
          status: "正常",
          createTime: "2021-01-01 10:10:10",
        },

        {
          date: "4",
          name: "10.03.09",
          address: "sys_job_group",
          status: "正常",
          createTime: "2021-01-01 08:10:10",
        },
      ],
      multipleSelection: [],
      btnDisabled: true,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableHeight: 550,
      value: "",
      options: [],
    };
  },
  computed: {
    isSuperAdmin() {
      return isSuperAdmin();
    },
  },
  mounted() {
    this.calculateTableHeight();
    this.loadDictData("sys_device_type", "options");
    this.initTable();
  },
  methods: {
    initTable() {},
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.btnDisabled = false;
      } else {
        this.btnDisabled = true;
      }
      console.log(this.multipleSelection);
    },
    handleClick(row, field) {
      switch (field) {
        // 设置更新范围
        case "updateSet":
          this.field = `升级${row.name}的SN号范围列表`;
          this.updateRangeVisible = true;
          break;
        case "edit":
          this.field = "修改固件版本";
          this.dialogVisible = true;
          break;
        case "add":
          this.field = "添加固件版本";
          this.dialogVisible = true;
          break;
        case "delete":
          this.$confirm(
            `确认删除选中的${this.multipleSelection.length}个设备吗?`,
            "系统提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
          break;
        case "run":
          this.$confirm(`确认要立即执行一次任务吗?`, "系统提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.$message({
              type: "success",
              message: "执行成功!",
            });
          });
          break;
        default:
          break;
      }
    },
    async loadDictData(dictType, targetProperty) {
      try {
        // 调用 store 中的字典查询方法，传入字典类型
        const data = await this.$store.dispatch("dict/queryDictData", dictType);
        // 根据接口返回的数据格式进行处理

        this[targetProperty] = [{ dictLabel: "所有", dictValue: "" }, ...data];
      } catch (error) {
        this.$message.error("获取数据失败");
      }
    },
    // 处理表头显示隐藏
    handleCheckChange(checkedValues) {
      this.tableHeader.forEach((item) => {
        item.visible = checkedValues.includes(item.prop);
      });
      this.tableKey += 1;
    },
    handleSearchClick() {
      this.searchCardShow = !this.searchCardShow;
      console.log("搜索按钮点击");
    },
    handleInitClick() {
      this.initTable();
    },
    handlerPagination(page) {
      this.currentPage = page.pageNum;
      this.pageSize = page.pageSize;
      this.initTable();
    },
    hasPermission(permission) {
      return hasPermission(permission);
    },
    calculateTableHeight() {
      // 根据容器实际高度计算表格高度
      this.$nextTick(() => {
        const container = this.$refs.multipleTable.$el?.parentElement;
        if (container) {
          // 减去表头和其他元素的高度
          this.tableHeight = container.clientHeight - 120; // 120为估计的其他元素高度
        }
      });
    },
  },
};
</script>
